<?php

namespace App\Http\Controllers;

use App\Models\BookInfo;
use App\Models\Category;
use App\Models\File;
use App\Models\Product;
use App\Models\ProductInfo;
use App\Models\Resource;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ProductController extends Controller
{

    /**
     * 查询产品详细,返回json格式
     */
    public function getDetail($id){
        $product = DB::table('products')->select('id','name')->where('id',$id)->first()??'';
        
        return response()->json([
            'error'=>0,
            'msg'=>'',
            'data'=>$product
        ]);
    }

    public function getList(Request $request)
    {
        $q = $request->input('q');

        return Product::where('name', 'like', "%$q%")->where('auditing_status', 'online')->paginate(null, ['id', 'name as text']);
    }

    public function getBookGradeInfo(Request $request)
    {
        $pid = $request->input('q');
        return BookInfo::where('pid', $pid)->get(['id', DB::raw('title as text')]);
    }


    public function getIndex(Request $request)
    {
        $param = $request->all();
        $keyword = $request->input('keyword');
        $catFilter = $request->input('L');
        $child = $request->input('C');
        $categoryId = $request->input('category_id');
        $resourceId = $request->input('resource_id');
        $specialFilter = false;
        $order = $request->input('order', 'push');

        $categorys = Category::select('id', 'name')
            ->where('p_id', 0)
            ->with(['children' => function($query) {
                $query->select('id', 'name', 'p_id');
            }])
            ->get();

        if (count($categorys) > 0)
        {
            if ($categoryId)
            {
                $cat = Category::select('id', 'name')->find($categoryId);
            } else {
                if (!$keyword) {
                    $categoryC = $categorys[0]->children;
                    if (count($categoryC) > 0) {
                        $cat = $categoryC[0];
                        $categoryId = $cat->id;
                    }
                }
            }

            if (!isset($cat) || !$cat)
            {
                $filter = null;
            } else {
                $cat->load(['children' => function($q) {
                    $q->select('id', 'name', 'p_id')
                        ->with(['children' => function($query) {
                            $query->select('id', 'name', 'p_id');
                        }]);
                }]);
                $filter = $cat->children;
                $filterArray = array_filter(array_pluck($filter->toArray(), 'children'));
                if (count($filterArray) == 0)
                {
                    $filter = Category::select('id', 'name')
                        ->with(['children' => function($q) {
                            $q->select('id', 'name', 'p_id');
                        }])
                        ->where('id', $categoryId)
                        ->get();
                    $specialFilter = true;
                }
            }
        }

        $searchArr = [];
        $multipleArr = [];
        $twoMultipleArr = [];
        $delVal = null;

        if (!isset($param['C']))
        {
            $param['C'] = null;
            $selectArr = [];
        } elseif (empty($param['C']) && $keyword && !$categoryId && !$catFilter && !$child && !$resourceId) {
            $selectArr = [];
        } else {
            $arr = array_filter(explode(',', $child));
            $uniqueArr = array_unique($arr);
            $cancelSelect = array_diff_assoc($arr, $uniqueArr);

            //重复选择某一个分类则取消选择
            if ($cancelSelect)
            {
                foreach ($cancelSelect as $key => $value)
                {
                    $val = Category::select('id', 'name', 'p_id')
                        ->with('parent')
                        ->find($value);

                    if (strstr($val->parent->name, '阶段'))
                    {
                        $valChildren = $val->children->pluck('id')->toArray();
                        foreach ($valChildren as $key => $child)
                        {
                            unset($uniqueArr[array_search($child, $uniqueArr)]);
                        }
                    }
                    unset($uniqueArr[array_search($value, $uniqueArr)]);
                }
            }

            if ($catFilter)
            {
                $catFilter = $filter->find($catFilter);
                if ($catFilter)
                {
                    $catFilterChildren = $catFilter->children;
                    foreach ($catFilterChildren as $key => $catFilterChild)
                    {
                         if (strstr($catFilter->name, '阶段'))
                         {
                             $unsetIds = $catFilterChild->children->pluck('id');
                             foreach ($unsetIds as $k => $unsetId)
                             {
                                 unset($uniqueArr[array_search($unsetId, $uniqueArr)]);
                             }
                         }
                        unset($uniqueArr[array_search($catFilterChild->id, $uniqueArr)]);
                    }
                }
            }

            //单个分类只允许选择一个
            foreach ($filter as $key => $item)
            {
                $itemChildren = $item->children;
                $itemIds = $itemChildren->pluck('id')->toArray();
                $intersectArr = array_values(array_intersect($uniqueArr, $itemIds));
                $intersectNum = count($intersectArr);

                if (strstr($item->name, '阶段') && $intersectNum == 1)
                {
                    $stageIds = Category::whereIn('p_id', $itemIds)->pluck('id')->toArray();
                    $intersectArr = array_values(array_intersect($uniqueArr, $stageIds));
                    $intersectNum = count($intersectArr);
                }

                if ($intersectNum > 1)
                {
                    foreach ($intersectArr as $k => $value)
                    {
                        $intSub = array_search($value, $intersectArr);

                        if ($intSub != ($intersectNum - 1))
                        {
                            if (strstr($item->name, '阶段'))
                            {
                                $valueIds = Category::where('p_id', $value)->pluck('id')->toArray();
                                $delIds = array_intersect($uniqueArr, $valueIds);
                                foreach ($delIds as $delId)
                                {
                                    unset($uniqueArr[array_search($delId, $uniqueArr)]);
                                }
                            }
                            $sub = array_search($value, $uniqueArr);
                            unset($uniqueArr[$sub]);
                        }
                    }
                }

                if (array_intersect($uniqueArr, $itemIds) && strstr($item->name, '阶段'))
                {
                    $stageId = implode(array_intersect($uniqueArr, $itemIds));

                    $grades = Category::where('p_id', $stageId)->select('id', 'name')->get();
                    $item->grades = $grades;

                    $gradeIds = $grades->pluck('id')->toArray();
                    $delVal = $stageId;

                    if (!array_intersect($uniqueArr, $gradeIds))
                        $multipleArr = $gradeIds;
                }
            }
            $searchArr = array_merge($searchArr, $uniqueArr);
            $selectArr = $uniqueArr;
            $param['C'] = implode($uniqueArr, ',');
        }

        if (count($searchArr) == 0 && count($multipleArr) == 0 && $categoryId)
        {
            $arr = Category::select('id', 'p_id')->get()->toArray();
            $twoMultipleArr = array_pluck($this->getMenuTree($arr, $categoryId), 'id');
            $twoMultipleArr[] = intval($categoryId);
        }

        if ($delVal)
            unset($searchArr[array_search($delVal, $searchArr)]);

        $resources = Resource::select('id', 'name', 'icon_url')
            ->where('status', 'enabled')
            ->get();

        $products = Product::select('products.id', 'uuid', 'name', 'cover', 'buy_link', 'buy_switch')
            ->where('auditing_status', 'online')
            ->with(['resources' => function($query) {
                $query->select('resources.id', 'name', 'icon_url');
            }]);

        if ($keyword)
            $products = $products->where('name','like', '%' . $keyword . '%');

        if (!$searchArr && !$multipleArr && $twoMultipleArr)
        {
            $products = $products->whereHas('categorys', function ($q) use ($twoMultipleArr) {
                    $q->whereIn('product_categorys.category_id', $twoMultipleArr);
                });
        }

        if (count($searchArr) != 0 || count($multipleArr) > 0)
        {
            if ($searchArr)
            {
                $products = $products->whereHas('categorys', function ($query) use ($searchArr) {
                    $query->whereIn('category_id', $searchArr);
                }, '=', count($searchArr));
            }

            if ($multipleArr)
            {
                $products = $products->whereHas('categorys', function ($query) use ($multipleArr) {
                    $query->whereIn('category_id', $multipleArr);
                });
            }

        }
        if ($resourceId)
        {
            $resourceId = intval($resourceId);
            $products = $products->whereHas('resources', function ($query) use($resourceId) {
                $query->select('product_resources.resource_id');
                $query->where('resource_id', $resourceId);
            });
        }

        if ($order == 'created') {
            $products = $products->orderBy('products.created_at', 'desc');
        } else {
            $products = $products->join('product_details as pd', 'pd.product_id', '=', 'products.id')
                ->orderBy('pd.date', 'desc');

        }
        $products = $products->paginate();
//        dd( DB::getQueryLog());

        if (!isset($param['order'])) $param['order'] = $order;

        foreach ($products as $key => $product)
        {
            unset($product->id);
            $products[$key] = $product;
        }
        unset($param['L']);
        unset($param['_token']);

        return view('product.index', [
            'param' => $param,
            'categorys' => $categorys,
            'resources' => $resources,
            'products' => $products,
            'filter' => $filter,
            'selectArr' => $selectArr,
            'categoryId' => $categoryId,
            'specialFilter' => $specialFilter,
        ]);
    }

    public function getInfo($uuid, Request $request)
    {
        $language = $request->input('language');

        $product = Product::select('id', 'uuid', 'category_id', 'name', 'summary', 'cover', 'press', 'pictures',
            'buy_link', 'author', 'author_about', 'introduce', 'remark', 'recommend', 'buy_switch')
            ->where('auditing_status', 'online')
            ->where('uuid', $uuid)
            ->first();

        if (!$product)
            return redirect('pageerror');

        $product = $product->load(
            [
                'details' => function ($query) {
                    $query->select('product_id', 'grade', 'upc', 'pages', 'date', 'isbn', 'package', 'format',
                        'material', 'priced', 'is_game');
                },
                'resources' => function ($query) {
                    $query->select('name', 'icon_url');
                },
                'files' => function ($query) {
                    $query->select('id', 'product_id', 'title', 'tryout', 'category', 'external', 'cover', 'local')
                        ->where(function ($q) {
                            $q->whereNotNull('tryout')
                                ->orWhereNotNull('external');
                        })
                        ->orderBy('created_at', 'asc')
                        ->whereIn('category', ['video', 'audio'])
                        ->groupBy('category')
                        ->get();
                }
            ]
        );

        foreach ($product->resources as $key => $resource)
        {
            unset($resource->pivot);
            $product->resources[$key] = $resource;
        }

        $product->tryout_video = null;
        $product->tryout_audio = null;
        if ($product->files)
        {
            foreach ($product->files as $key => $file)
            {
                if ($file->category == 'video')
                {
                    $product->tryout_video = $file;
                } else {
                    $product->tryout_audio = $file;
                }
            }
            unset($product->files);
        }
        $sameGradeBooks = false;

        $category = Category::select('id', 'name', 'p_id', 'level')->find($product->category_id);

        $categoryNav = [];
        if ($category)
        {
            if ($category->level == 1)
            {
                $category = $category->children()->pluck('id');
                $category = Category::whereIn('p_id', $category)->where('name', 'like', '%阶段%')->first();
            } else {
                $category = $category->children()->where('name', 'like', '%阶段%')->first();
            }

            $intersectArr = [];
            if (isset($category->children) && count($category->children)) {
                $categoryIds = $category->children->pluck('id');
                $geadeIds = Category::whereIn('p_id', $categoryIds)->pluck('id')->toArray();
                $productCatrgory = $product->categorys->pluck('id')->toArray();
                $intersectArr = array_intersect($geadeIds, $productCatrgory);
            }
            if (count($intersectArr) > 0)
            {
                $sameGradeBooks = Product::select('id', 'uuid', 'name', 'cover')
                    ->whereHas('categorys', function ($q) use($intersectArr) {
                        $q->whereIn('category_id', $intersectArr);
                    })
                    ->where('auditing_status', 'online')
                    ->where('id', '<>', $product->id)
                    ->inRandomOrder()
                    ->take(10)
                    ->get();

                foreach ($sameGradeBooks as $key => $value)
                {
                    unset($sameGradeBooks[$key]->id);
                }
                if (count($sameGradeBooks) <= 0)
                    $sameGradeBooks = false;

            }
            $categoryNav = $this->getCategoryNav($product->category_id);
        }

        if ($language == 'en')
        {
            return view('en.product_detail',
                [
                    'product' => $product,
                    'categoryNav' => $categoryNav,
                ]
            );
        }
        return view('product.detail',
            [
                'product' => $product,
                'categoryNav' => $categoryNav,
                'sameGradeBooks' => $sameGradeBooks
            ]
        );
    }

    public function getEnglishInfo($uuid, Request $request)
    {

        return view('en.product_detail');
    }

    public function getCategoryNav($categoryId)
    {
        $category = Category::select('id', 'name', 'p_id', 'level')->get();

        $categoryArr = $category->pluck('p_id', 'id')->toArray();

        $parentIds = [];
        while ($categoryId)
        {
            $parentIds[] = $categoryId;
            $categoryId = $categoryArr[$categoryId];
        }
        $categoryData = $category->whereIn('id', $parentIds)->pluck('name', 'id');

        $record = array_reverse($parentIds);
        $categoryNav = [];
        foreach ($record as $key => $value)
        {
            $categoryNav[] =
                [
                    'id' => $value,
                    'title' => $categoryData[$value]
                ];
        }

        return $categoryNav;
    }
}